package com.zhangsun.yueBoot.framework.handler;

import com.alibaba.fastjson.JSON;
import com.zhangsun.yueBoot.commons.base.bean.ResponseResult;
import com.zhangsun.yueBoot.commons.logger.MyLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆失败处理
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private MyLoggerFactory logger;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.error("登陆失败：" + e.getMessage());
        logger.error(e);
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();

        String message = "工号或密码错误";
        if (e instanceof UsernameNotFoundException) {
            message = e.getMessage();
        } else if (e instanceof LockedException) {
            message = "账号被锁定";
        }
        ResponseResult responseResult = ResponseResult.error("500", "登陆失败：" + message);
        printWriter.write(JSON.toJSONString(responseResult));
        printWriter.flush();
    }
}
